package mutil

import (
	"fmt"
	"io/ioutil"
	"mime/multipart"
	"os"
	"path"
	"strings"
)

var Upload = &upload{}

type upload struct {
}

func (domain *upload) SystemLocalFileStorage(multipartFile multipart.File, size int64, basePath string, storageFilename string) (writePath string, errs error) {
	fileBytes := make([]byte, size)
	_, err := multipartFile.Read(fileBytes)
	if err != nil {
		return "", err
	}
	if strings.LastIndexAny(basePath, `/`) == len(basePath)-1 {
		basePath = basePath[0 : len(basePath)-1]
	}
	dateStr := DateUtil.NowDateTime().Format(DateUtil.DateFormatNumber)
	filename := fmt.Sprintf("%s%s", RandomUtil.UniqueId(fmt.Sprintf("%s-", RandomUtil.NextXAZ(1)), 26), path.Ext(storageFilename))
	filepath := fmt.Sprintf("%s/%s/", basePath, dateStr)
	_, err = os.Stat(filepath)
	if os.IsNotExist(err) {
		os.MkdirAll(filepath, 0666)
	}
	writePath = fmt.Sprintf("%s%s", filepath, filename)
	return fmt.Sprintf("/%s/%s", dateStr, filename), ioutil.WriteFile(writePath, fileBytes, 0666)
	return "", nil
}
